package com.ruoyi.classai.service.impl;


import cn.hutool.crypto.digest.DigestUtil;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.yulichang.base.MPJBaseServiceImpl;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.ruoyi.classai.domain.EwcClassStudent;
import com.ruoyi.classai.domain.EwcStudent;
import com.ruoyi.classai.domain.dto.EwcStudentDto;
import com.ruoyi.classai.domain.dto.EwcStudentExportDto;
import com.ruoyi.classai.mapper.EwcStudentMapper;
import com.ruoyi.classai.service.IEwcClassStudentService;
import com.ruoyi.classai.service.IEwcStudentService;
import com.ruoyi.common.core.constant.Constants;
import com.ruoyi.common.core.exception.GlobalException;
import com.ruoyi.common.core.utils.poi.ExcelUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * 学生信息Service业务层处理
 * 
 * @author lcj
 * @date 2025-02-27
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class EwcStudentServiceImpl extends MPJBaseServiceImpl<EwcStudentMapper, EwcStudent> implements IEwcStudentService {

    @Autowired
    private IEwcClassStudentService classStudentService;
    @Autowired
    private EwcStudentMapper studentMapper;

    @Override
    public void add(EwcStudentDto student) {
        //查询学号是否存在
        EwcStudent ewcStudent=this.getOne(Wrappers.<EwcStudent>lambdaQuery().eq(EwcStudent::getStudentNo,student.getStudentNo()));
        if (Objects.nonNull(ewcStudent)){ //学生已存在
            //判断学生是否关联此班级
            EwcClassStudent classStudent=classStudentService.getOne(Wrappers.<EwcClassStudent>lambdaQuery().eq(EwcClassStudent::getStudentId,ewcStudent.getId())
                    .eq(EwcClassStudent::getClassId,student.getClassId()));
            if (Objects.nonNull(classStudent)) {
                throw new GlobalException("学生已存在不能重复添加");
            }
            //添加学生班级关联
            classStudent=new EwcClassStudent();
            classStudent.setClassId(student.getClassId());
            classStudent.setStudentId(ewcStudent.getId());
            classStudent.setGroupId(student.getGroupId());
            //修改学生状态
            classStudent.setStatus(student.getStatus());
            classStudentService.save(classStudent);
        }else {
            ewcStudent=new EwcStudent();
            BeanUtils.copyProperties(student,ewcStudent);
            //设置初始密码
            ewcStudent.setPassword(DigestUtil.md5Hex(Constants.INITIAL_PASSWORD));
            //添加学生信息
            this.save(ewcStudent);
            //添加学生班级关联
            EwcClassStudent classStudent=new EwcClassStudent();
            classStudent.setClassId(student.getClassId());
            classStudent.setStudentId(ewcStudent.getId());
            classStudent.setGroupId(student.getGroupId());
            //添加学生状态
            classStudent.setStatus(student.getStatus());
            classStudentService.save(classStudent);
        }
    }

    @Override
    public void edit(EwcStudentDto student) {
        EwcStudent ewcStudent=new EwcStudent();
        BeanUtils.copyProperties(student,ewcStudent);
        this.updateById(ewcStudent);
        //删除关联
        classStudentService.remove(Wrappers.<EwcClassStudent>lambdaQuery().eq(EwcClassStudent::getStudentId,student.getId()));
        //添加学生班级关联
        EwcClassStudent classStudent=new EwcClassStudent();
        classStudent.setClassId(student.getClassId());
        classStudent.setStudentId(student.getId());
        classStudent.setGroupId(student.getGroupId());
        //添加学生状态
        classStudent.setStatus(student.getStatus());
        classStudentService.save(classStudent);
    }

    @Override
    public void deleteStudent(String studentId,String classId) {
        classStudentService.remove(Wrappers.<EwcClassStudent>lambdaQuery()
                .eq(EwcClassStudent::getStudentId,studentId)
                .eq(EwcClassStudent::getClassId,classId));
    }

    @Override
    public List<EwcStudentDto> getList(String studentName,String classId) {
        MPJLambdaWrapper<EwcStudent> wrapper= new MPJLambdaWrapper<>();
        wrapper.selectAll(EwcStudent.class)
                .select(EwcClassStudent::getStatus,EwcClassStudent::getGroupId,EwcClassStudent::getClassId)
                .innerJoin(EwcClassStudent.class,EwcClassStudent::getStudentId,EwcStudent::getId)
                .eq(EwcClassStudent::getClassId, classId)
                .like(StringUtils.isNotEmpty(studentName),EwcStudent::getStudentName,studentName)
                .orderByAsc(EwcStudent::getCreateTime);
        // 执行查询并返回结果列表
        return this.selectJoinList(EwcStudentDto.class, wrapper);
    }

    @Override
    public JSONObject importStudent(MultipartFile file, String classId) {
        ExcelUtil<EwcStudentExportDto> util = new ExcelUtil<>(EwcStudentExportDto.class);
        List<EwcStudentExportDto> studentList;
        try {
            studentList = util.importExcel(file.getInputStream());
        } catch (IOException e) {
            throw new GlobalException(e.getMessage());
        }
        //成功
        List<String> successList=new ArrayList<>();
        //失败
        List<String> failList=new ArrayList<>();
        //学生dto循环
        for (EwcStudentExportDto ewcStudentExportDto : studentList) {
            if (StringUtils.isNotEmpty(ewcStudentExportDto.getStudentName())&&StringUtils.isNotEmpty(ewcStudentExportDto.getStudentNo())
            &&StringUtils.isNotEmpty(ewcStudentExportDto.getGender())&&StringUtils.isNotEmpty(ewcStudentExportDto.getMobileNo())) {
                //查询学生是否存在
                EwcStudent ewcStudent = this.getOne(Wrappers.<EwcStudent>lambdaQuery().eq(EwcStudent::getStudentNo, ewcStudentExportDto.getStudentNo()));
                if(Objects.nonNull(ewcStudent)){
                    //判断学生是否关联此班级
                    EwcClassStudent classStudent=classStudentService.getOne(Wrappers.<EwcClassStudent>lambdaQuery().eq(EwcClassStudent::getStudentId,ewcStudent.getId())
                            .eq(EwcClassStudent::getClassId,classId));
                    if (Objects.nonNull(classStudent)) {
                        EwcStudent ewcStudent1 = new EwcStudent();
                        ewcStudent1.setId(ewcStudent.getId());
                        BeanUtils.copyProperties(ewcStudentExportDto, ewcStudent1);
                        //设置初始密码
                        ewcStudent1.setPassword(DigestUtil.md5Hex(Constants.INITIAL_PASSWORD));
                        //更新学生信息
                        this.updateById(ewcStudent1);
                        failList.add(ewcStudentExportDto.getStudentName()+"学生已存在,已更新");
                    }else {
                        //添加学生班级关联
                        EwcClassStudent classStudent1=new EwcClassStudent();
                        classStudent1.setClassId(classId);
                        classStudent1.setStudentId(ewcStudent.getId());
                        //分组Id
                        classStudent1.setGroupId(ewcStudentExportDto.getGroupId());
                        //学生状态
                        if (StringUtils.isNotEmpty(ewcStudentExportDto.getStatus())){
                            classStudent1.setStatus(Objects.equals(ewcStudentExportDto.getStatus(),"正常")?1:2);
                        }
                        classStudentService.save(classStudent1);
                        successList.add(ewcStudentExportDto.getStudentName()+"学生信息添加成功");
                    }
                }else {
                    ewcStudent = new EwcStudent();
                    BeanUtils.copyProperties(ewcStudentExportDto, ewcStudent);
                    //设置初始密码
                    ewcStudent.setPassword(DigestUtil.md5Hex(Constants.INITIAL_PASSWORD));
                    this.save(ewcStudent);
                    //添加学生班级关联
                    EwcClassStudent classStudent=new EwcClassStudent();
                    classStudent.setClassId(classId);
                    classStudent.setStudentId(ewcStudent.getId());
                    //分组Id
                    classStudent.setGroupId(ewcStudentExportDto.getGroupId());
                    //学生状态
                    if (StringUtils.isNotEmpty(ewcStudentExportDto.getStatus())){
                        classStudent.setStatus(Objects.equals(ewcStudentExportDto.getStatus(),"正常")?1:2);
                    }
                    classStudentService.save(classStudent);
                    successList.add(ewcStudentExportDto.getStudentName()+"学生信息添加成功");
                }
            }else {
                failList.add(ewcStudentExportDto.getStudentName()+"学生上传失败,学生信息不完善");
            }
        }
        JSONObject resJson=new JSONObject();
        resJson.put("successList",successList);
        resJson.put("failList",failList);
        return resJson;
    }

    @Override
    public int getStudentNumberBySex(String classId, String sex) {
        return studentMapper.getStudentNumberBySex(classId,sex);
    }


}
